//
//  ElephantMainViewController.m
//  MyProject
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "ElephantMainViewController.h"
#import "Eletanph.h"
#import "ETableViewCell.h"
#import "ETCollectionViewCell.h"
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import "HandleData.h"
#import "ElephantWebViewController.h"
#import "MBProgressHUD.h"
#define ScreenWidth self.view.bounds.size.width
#define Screenheight self.view.bounds.size.height
@interface ElephantMainViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate,MBProgressHUDDelegate>
@property (nonatomic, strong) NSMutableArray *useArr;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableDictionary *pageIdDic;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageS;
@property (nonatomic, strong) UIView *LineView;
@property (nonatomic, strong) UILabel *pageL;
@property (nonatomic, strong) UILabel *ShuaXinLabel;
@property (nonatomic,strong) NSMutableArray *articleArr;
@property (nonatomic, strong) ETableViewCell *nowCell;
@property (nonatomic,strong) UIView *myview;

@end

@implementation ElephantMainViewController
- (void)viewWillAppear:(BOOL)animated
{
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
        
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
         }
    else {
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.barTintColor = [UIColor redColor];
        
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
           }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    

    self.view.backgroundColor = [UIColor whiteColor];
    
    
    UILabel *NoticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, Screenheight - 100, ScreenWidth, 50)];
    NoticeLabel.textAlignment = NSTextAlignmentCenter;
    NoticeLabel.text = @"横向滑动换下一篇文章";
    [self.view addSubview:NoticeLabel];

    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 25, ScreenWidth, Screenheight) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.pagingEnabled = YES;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self NewdataHandler];
        [_collectionView setContentOffset:CGPointMake(0, 0) animated:NO];
        [_tableView.header endRefreshing];
    }];
    [header setTitle:@"加载更多" forState:MJRefreshStatePulling];
    _tableView.header = header;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(ScreenWidth, Screenheight - 100);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, Screenheight - 100) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[ETCollectionViewCell class] forCellWithReuseIdentifier:@"ET"];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    _collectionView.bounces = NO;
    
    //滚动的线
    self.LineView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth / 6, 2)];
    _LineView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_LineView];
  
    
    self.ShuaXinLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, ScreenWidth - 100, 20)];
    _ShuaXinLabel.text = @"下拉加载更多";
    _ShuaXinLabel.textAlignment = NSTextAlignmentCenter;
        _ShuaXinLabel.textColor = [UIColor grayColor];
    _ShuaXinLabel.font = [UIFont systemFontOfSize:15];
    _ShuaXinLabel.layer.borderWidth = 1;
    _ShuaXinLabel.layer.cornerRadius = 5;
    [self.view addSubview:_ShuaXinLabel];
    
    self.page = 1;
    
    [self dataHandler];
  
}
- (void)NewdataHandler
{
    self.page = _page + 1;
    NSLog(@"%d", self.page);
    NSString *str = [NSString stringWithFormat:@"http://app.idaxiang.org/api/v1_0/art/list?pageSize=6&page=%d",self.page];
     [HandleData handleDataWithUrl:str completion:^(id data) {
         
         self.useArr = [NSMutableArray array];
         NSDictionary *AllDic = [data objectForKey:@"body"];
         NSMutableArray *arr = [AllDic objectForKey:@"article"];
         for (NSMutableDictionary *dic in arr) {
             
             Eletanph *ele = [[Eletanph alloc] init];
             [ele setValuesForKeysWithDictionary:dic];
                 [self.useArr addObject:ele];
             
         }
         
         
         [_tableView reloadData];
         [_collectionView reloadData];
         
         
     }];
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat Num = (_collectionView.contentOffset.x / ScreenWidth);
    self.pageS = (NSInteger)Num;
    _LineView.frame = CGRectMake(ScreenWidth / 6 * _pageS, 64, ScreenWidth / 6, 2);
    
    Eletanph *ele = [self.useArr objectAtIndex:_pageS];
//    NSLog(@"%@", _nowCell);
    _nowCell.titleLabel.text = ele.title;
    _nowCell.authorLabel.text = ele.author;
    _nowCell.briefLabel.text = ele.brief;
//    NSLog(@"=====%@ %@ %@", _nowCell.titleLabel.text, _nowCell.authorLabel.text, _nowCell.briefLabel.text);
//    [_tableView reloadData];
    
    if (_collectionView.contentOffset.x / ScreenWidth == 5) {
        NSLog(@"shuaxin");
        
        [UIView animateWithDuration:1 animations:^{
            _ShuaXinLabel.frame = CGRectMake(50, 70, ScreenWidth - 100, 20);
        }];
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(backAction) userInfo:nil repeats:NO];
//        [self backAction];
    }
}

- (void)backAction
{
    [UIView animateWithDuration:0.5 animations:^{
        _ShuaXinLabel.frame = CGRectMake(50, 0, ScreenWidth - 100, 20);
    }];
}

// tableV 点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ElephantWebViewController *eleVC = [[ElephantWebViewController alloc]init];
    Eletanph *ele = [self.useArr objectAtIndex:indexPath.row];
    eleVC.newid = ele.useid;
    eleVC.url = ele.wechat_url;
    eleVC.needtitle = ele.title;
    eleVC.headpic = ele.headpic;
//    NSLog(@"QWERT%@",eleVC.newid);
//    NSLog(@"DFG%@",eleVC.url);
    [self.navigationController pushViewController:eleVC animated:YES];
    }
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 6;
}

// collection cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ETCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ET" forIndexPath:indexPath];
    Eletanph *artE = [self.useArr objectAtIndex:indexPath.row];
    
    [cell.headpic sd_setImageWithURL:[NSURL URLWithString:artE.headpic]placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
    [cell.footpic sd_setImageWithURL:[NSURL URLWithString:artE.headpic]placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
    
//    NSTimeInterval *time = (NSTimeInterval *)artE.create_time;
//    NSDate *createD = [NSDate dateWithTimeInterval:*time sinceDate:[NSDate date]];
//    NSLog(@"%@", createD);
//    NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
//    dateF.dateFormat = @"yyyy.MM.dd";
//    
//    cell.create_time.text = [dateF stringFromDate:createD];
//    cell.read_num.text = artE.read_num;
    
    return cell;
}

// tableV cell数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return Screenheight - 100;
}

// tableV cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ETableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hello"];
    if (!cell) {
        cell = [[ETableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"hello"];
    }
    if (self.useArr.count != 0) {
        
        self.nowCell = cell;
        [cell.bgView addSubview:_collectionView];
        Eletanph *ele = [self.useArr objectAtIndex:indexPath.row];
        cell.titleLabel.text = ele.title;
        cell.authorLabel.text = ele.author;
        cell.briefLabel.text = ele.brief;
        

        if (![[NSUserDefaults standardUserDefaults] boolForKey:@"isWhite"]) {
            cell.titleLabel.textColor = [UIColor whiteColor];
            cell.authorLabel.textColor = [UIColor whiteColor];
            cell.briefLabel.textColor = [UIColor whiteColor];
        }else{
            cell.titleLabel.textColor = [UIColor blackColor];
            cell.authorLabel.textColor = [UIColor blackColor];
            cell.briefLabel.textColor = [UIColor blackColor];
            
        }
    }
    
    return cell;
}

// 数据处理
- (void)dataHandler
{
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.delegate = self;
//        HUD.color = [UIColor blackColor];
        HUD.labelText = @"loading";
        HUD.detailsLabelText = @"网络加载中,请稍等";
//        HUD.dimBackground = YES;
       [HandleData handleDataWithUrl:@"http://app.idaxiang.org/api/v1_0/art/list?pageSize=6&page=0" completion:^(id data)
     {
         
         if (data) {
                         [HUD hide:YES afterDelay:0];
                     }
             NSDictionary *AllDic = [data objectForKey:@"body"];
             NSMutableArray *arr = [AllDic objectForKey:@"article"];
             self.useArr = [NSMutableArray array];
             for (NSMutableDictionary *dic in arr) {
                 
                 Eletanph *ele = [[Eletanph alloc] init];
                 [ele setValuesForKeysWithDictionary:dic];
                 
                 [self.useArr addObject:ele];
  
             }
         
         
             [_tableView reloadData];
             [_collectionView reloadData];
             
         
         }];
    
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
